<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview" v-loading="loading.overview">
      <el-col :span="6" v-for="(item, index) in overviewData" :key="index">
        <el-card shadow="hover" class="overview-card" :body-style="{ padding: '20px' }">
          <div class="overview-card-header">
            <span class="overview-card-title">{{ item.title }}</span>
            <el-tag :type="item.type" size="small">{{ item.trend }}</el-tag>
          </div>
          <div class="overview-card-content">
            <span class="overview-card-value">{{ item.value }}</span>
            <span class="overview-card-unit">{{ item.unit }}</span>
          </div>
          <div class="overview-card-footer">
            <span class="overview-card-compare">
              较昨日
              <span :class="['compare-value', item.compare >= 0 ? 'up' : 'down']">
                {{ Math.abs(item.compare) }}%
                <el-icon>
                  <component :is="item.compare >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待处理事项 -->
    <el-row :gutter="20" class="pending-tasks" v-loading="loading.tasks">
      <el-col :span="24">
        <el-card shadow="hover" class="task-card">
          <template #header>
            <div class="task-card-header">
              <span class="task-card-title">待处理事项</span>
              <el-button type="primary" link>查看全部</el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="4" v-for="(task, index) in pendingTasks" :key="index">
              <div class="task-item" @click="handleTaskClick(task)">
                <div class="task-item-value">{{ task.value }}</div>
                <div class="task-item-label">{{ task.label }}</div>
                <el-badge v-if="task.badge" :value="task.badge" class="task-item-badge" />
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 销售趋势图 -->
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card" v-loading="loading.salesTrend">
          <template #header>
            <div class="chart-card-header">
              <span class="chart-card-title">销售趋势</span>
              <el-radio-group v-model="salesTrendType" size="small" @change="handleTrendTypeChange">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="salesTrendChartRef"></div>
        </el-card>
      </el-col>

      <!-- 商品分类销售占比 -->
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card" v-loading="loading.categorySales">
          <template #header>
            <div class="chart-card-header">
              <span class="chart-card-title">商品分类销售占比</span>
            </div>
          </template>
          <div class="chart-container" ref="categorySalesChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热销商品排行 -->
    <el-row :gutter="20" class="hot-goods">
      <el-col :span="24">
        <el-card shadow="hover" class="goods-card" v-loading="loading.hotGoods">
          <template #header>
            <div class="goods-card-header">
              <span class="goods-card-title">热销商品排行</span>
              <el-radio-group v-model="hotGoodsType" size="small" @change="handleHotGoodsTypeChange">
                <el-radio-button label="sales">销量</el-radio-button>
                <el-radio-button label="amount">金额</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <el-table :data="hotGoodsList" style="width: 100%" :show-header="false">
            <el-table-column width="50">
              <template #default="scope">
                <div class="goods-rank" :class="{ 'top-three': scope.$index < 3 }">
                  {{ scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" min-width="300">
              <template #default="scope">
                <div class="goods-info">
                  <el-image 
                    :src="scope.row.image" 
                    :preview-src-list="[scope.row.image]"
                    fit="cover"
                    class="goods-image"
                  />
                  <span class="goods-name">{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column prop="sales" label="销量" width="120" align="right">
              <template #default="scope">
                {{ scope.row.sales }}件
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="销售额" width="120" align="right">
              <template #default="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
// 按需引入 echarts 核心模块
import * as echarts from 'echarts/core'
// 引入图表类型
import { LineChart, BarChart, PieChart } from 'echarts/charts'
// 引入提示框、标题、直角坐标系、数据集、内置数据转换器组件
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components'
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  LineChart,
  BarChart,
  PieChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])

const router = useRouter()
const salesTrendChartRef = ref(null)
const categorySalesChartRef = ref(null)
const salesTrendChart = shallowRef(null)
const categorySalesChart = shallowRef(null)
const salesTrendType = ref('week')
const hotGoodsType = ref('sales')

// 概览数据
const overviewData = ref([
  {
    title: '今日成交金额',
    value: '0.00',
    unit: '元',
    trend: '日',
    type: 'success',
    compare: 0
  },
  {
    title: '今日成交订单',
    value: '0',
    unit: '笔',
    trend: '日',
    type: 'warning',
    compare: 0
  },
  {
    title: '商品点击人数',
    value: '0',
    unit: '人',
    trend: '日',
    type: 'info',
    compare: 0
  },
  {
    title: '商品曝光人数',
    value: '0',
    unit: '人',
    trend: '日',
    type: 'primary',
    compare: 0
  }
])

// 待处理事项
const pendingTasks = ref([
  {
    label: '待支付订单',
    value: 0,
    type: 'order',
    badge: 0
  },
  {
    label: '待发货订单',
    value: 0,
    type: 'order',
    badge: 0
  },
  {
    label: '异常包裹',
    value: 0,
    type: 'logistics',
    badge: 0
  },
  {
    label: '待处理售后',
    value: 0,
    type: 'after-sales',
    badge: 0
  },
  {
    label: '待处理违规',
    value: 0,
    type: 'violation',
    badge: 0
  },
  {
    label: '待审核商品',
    value: 0,
    type: 'goods',
    badge: 0
  }
])

// 热销商品列表
const hotGoodsList = ref([])

// 加载状态
const loading = ref({
  overview: false,
  tasks: false,
  salesTrend: false,
  categorySales: false,
  hotGoods: false
})

// 图表配置
const chartOptions = {
  // 销售趋势图配置
  salesTrend: {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['销售额', '订单数'],
      right: 10,
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: {
        lineStyle: {
          color: '#909399'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#409EFF'
          }
        },
        axisLabel: {
          formatter: '{value} 元',
          color: '#606266'
        },
        splitLine: {
          lineStyle: {
            color: '#EBEEF5'
          }
        }
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#67C23A'
          }
        },
        axisLabel: {
          formatter: '{value} 笔',
          color: '#606266'
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64,158,255,0.3)'
            },
            {
              offset: 1,
              color: 'rgba(64,158,255,0.1)'
            }
          ])
        }
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  },
  // 分类销售占比图配置
  categorySales: {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}元 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      type: 'scroll',
      textStyle: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '销售占比',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }
}

// 更新销售趋势图
const updateSalesTrendChart = (data) => {
  if (!salesTrendChart.value) return
  
  const option = { ...chartOptions.salesTrend }
  option.xAxis.data = data.dates
  option.series[0].data = data.amounts
  option.series[1].data = data.orders
  
  salesTrendChart.value.setOption(option, true)
}

// 更新分类销售占比图
const updateCategorySalesChart = (data) => {
  if (!categorySalesChart.value) return
  
  const option = { ...chartOptions.categorySales }
  option.series[0].data = data.map(item => ({
    name: item.name,
    value: item.value
  }))
  
  categorySalesChart.value.setOption(option, true)
}

// 获取概览数据
const fetchOverviewData = async () => {
  loading.value.overview = true
  try {
    const res = await getMerchantOverview()
    const { data } = res
    
    overviewData.value = [
      {
        title: '今日成交金额',
        value: data.todayAmount.toFixed(2),
        unit: '元',
        trend: '日',
        type: 'success',
        compare: data.amountCompare
      },
      {
        title: '今日成交订单',
        value: data.todayOrders,
        unit: '笔',
        trend: '日',
        type: 'warning',
        compare: data.ordersCompare
      },
      {
        title: '商品点击人数',
        value: data.todayClicks,
        unit: '人',
        trend: '日',
        type: 'info',
        compare: data.clicksCompare
      },
      {
        title: '商品曝光人数',
        value: data.todayExposures,
        unit: '人',
        trend: '日',
        type: 'primary',
        compare: data.exposuresCompare
      }
    ]
  } catch (error) {
    console.error('获取概览数据失败:', error)
    ElMessage.error('获取概览数据失败')
  } finally {
    loading.value.overview = false
  }
}

// 获取待处理事项
const fetchPendingTasks = async () => {
  try {
    const res = await getMerchantPendingTasks()
    const { data } = res
    
    pendingTasks.value = [
      {
        label: '待支付订单',
        value: data.pendingPayOrders,
        type: 'order',
        badge: data.pendingPayOrders
      },
      {
        label: '待发货订单',
        value: data.pendingShipOrders,
        type: 'order',
        badge: data.pendingShipOrders
      },
      {
        label: '异常包裹',
        value: data.abnormalPackages,
        type: 'logistics',
        badge: data.abnormalPackages
      },
      {
        label: '待处理售后',
        value: data.pendingAfterSales,
        type: 'after-sales',
        badge: data.pendingAfterSales
      },
      {
        label: '待处理违规',
        value: data.pendingViolations,
        type: 'violation',
        badge: data.pendingViolations
      },
      {
        label: '待审核商品',
        value: data.pendingGoods,
        type: 'goods',
        badge: data.pendingGoods
      }
    ]
  } catch (error) {
    console.error('获取待处理事项失败:', error)
    ElMessage.error('获取待处理事项失败')
  }
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  loading.value.salesTrend = true
  try {
    const res = await getMerchantSalesTrend({ type: salesTrendType.value })
    updateSalesTrendChart(res.data)
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
    ElMessage.error('获取销售趋势数据失败')
  } finally {
    loading.value.salesTrend = false
  }
}

// 获取分类销售数据
const fetchCategorySales = async () => {
  loading.value.categorySales = true
  try {
    const res = await getMerchantCategorySales()
    updateCategorySalesChart(res.data)
  } catch (error) {
    console.error('获取分类销售数据失败:', error)
    ElMessage.error('获取分类销售数据失败')
  } finally {
    loading.value.categorySales = false
  }
}

// 获取热销商品数据
const fetchHotGoods = async () => {
  loading.value.hotGoods = true
  try {
    const res = await getMerchantHotGoods({ type: hotGoodsType.value })
    hotGoodsList.value = res.data
  } catch (error) {
    console.error('获取热销商品数据失败:', error)
    ElMessage.error('获取热销商品数据失败')
  } finally {
    loading.value.hotGoods = false
  }
}

// 处理趋势类型切换
const handleTrendTypeChange = () => {
  fetchSalesTrend()
}

// 处理热销商品类型切换
const handleHotGoodsTypeChange = () => {
  fetchHotGoods()
}

// 处理待处理事项点击
const handleTaskClick = (task) => {
  switch (task.type) {
    case 'order':
      router.push('/orders')
      break
    case 'logistics':
      router.push('/logistics')
      break
    case 'after-sales':
      router.push('/after-sales')
      break
    case 'violation':
      router.push('/violations')
      break
    case 'goods':
      router.push('/goods')
      break
  }
}

// 初始化图表
const initCharts = () => {
  if (salesTrendChartRef.value) {
    salesTrendChart.value = echarts.init(salesTrendChartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: true
    })
  }
  if (categorySalesChartRef.value) {
    categorySalesChart.value = echarts.init(categorySalesChartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: true
    })
  }
}

// 监听窗口大小变化
const handleResize = () => {
  salesTrendChart.value?.resize()
  categorySalesChart.value?.resize()
}

// 防抖处理
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

const debouncedResize = debounce(handleResize, 100)

onMounted(() => {
  initCharts()
  fetchOverviewData()
  fetchPendingTasks()
  fetchSalesTrend()
  fetchCategorySales()
  fetchHotGoods()
  
  window.addEventListener('resize', debouncedResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', debouncedResize)
  salesTrendChart.value?.dispose()
  categorySalesChart.value?.dispose()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.overview-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.overview-card-title {
  font-size: 14px;
  color: #909399;
}

.overview-card-content {
  margin-bottom: 12px;
}

.overview-card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.overview-card-unit {
  font-size: 14px;
  color: #909399;
  margin-left: 4px;
}

.overview-card-footer {
  font-size: 12px;
  color: #909399;
}

.compare-value {
  margin-left: 4px;
  font-weight: 500;
}

.compare-value.up {
  color: #67C23A;
}

.compare-value.down {
  color: #F56C6C;
}

.pending-tasks {
  margin-bottom: 20px;
}

.task-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.task-item {
  text-align: center;
  padding: 20px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.task-item:hover {
  background-color: #f5f7fa;
}

.task-item-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.task-item-label {
  font-size: 14px;
  color: #909399;
}

.task-item-badge {
  position: absolute;
  top: 10px;
  right: 10px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chart-container {
  height: 350px;
  position: relative;
}

.goods-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.goods-rank {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.goods-rank.top-three {
  color: #fff;
}

.goods-rank:nth-child(1) {
  background-color: #F56C6C;
}

.goods-rank:nth-child(2) {
  background-color: #E6A23C;
}

.goods-rank:nth-child(3) {
  background-color: #67C23A;
}

.goods-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.goods-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}

.goods-name {
  font-size: 14px;
  color: #303133;
}

:deep(.el-card__body) {
  padding: 20px;
}

.chart-card {
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

/* 添加图表加载动画 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
}

:deep(.el-loading-spinner) {
  .circular {
    width: 42px;
    height: 42px;
  }
}

/* 优化图表容器样式 */
.chart-section {
  .el-card {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    
    :deep(.el-card__header) {
      padding: 15px 20px;
      border-bottom: 1px solid #EBEEF5;
      background-color: #F5F7FA;
    }
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
}

/* 优化图表标题样式 */
.chart-card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409EFF;
    border-radius: 2px;
  }
}

/* 优化图表交互样式 */
:deep(.el-radio-group) {
  .el-radio-button__inner {
    padding: 8px 15px;
  }
}

/* 添加图表hover效果 */
.chart-card {
  &:hover {
    .chart-card-title::before {
      background-color: #67C23A;
    }
  }
}
</style> 